<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/24
 * Time: 15:03
 */
namespace app\admin\library;
use think\exception\HttpException;
use think\facade\Session;
use think\Db;
class Auth
{

    const USER = 'rbac_staff';
    const SUPER_ADMIN = 'admin';
    protected static $instance;
    protected $user;

    //是否是超级管理员
    protected $is_super=false;

    //单例模式
    public static function instance()
    {
        if (is_null(self::$instance))
        {
            self::$instance = new static();
        }

        return self::$instance;
    }

    //构造
    public function __construct()
    {
        $this->user = Session::get(self::USER);
        if($this->user == null){
            return;
        }

        if($this->user['username'] == self::SUPER_ADMIN){
            $this->is_super = true;
        }
    }

    //登录
    public function login($username,$password)
    {
        $user = Db::table('rbac_staff')->where(['username'=>$username,'password'=>md5($password)])->find();
        if($user == null){
            throw new HttpException(403,'用户名或密码不正确');
        }
        $this->user = $user;
        Session::set(self::USER,$user);
        if($this->user['username'] == self::SUPER_ADMIN){
            $this->is_super = true;
        }
    }

    //注销
    public function loginOut()
    {
        Session::set(self::USER,null);
    }

    //获取user数据
    public function getUser()
    {
        return $this->user;
    }

    //判断是否有权限
    public function hasAuth($path)
    {
        if($this->user == null){
           return false;
        }
        if($this->is_super){
            return true;
        }
        $role_id = $this->user['role_id'];
        if($role_id == null){
           return false;
        }
        $node_id = Db::table('rbac_node')->where('path',$path)->value('id');
        $count = Db::table('rbac_role_node')->where(['node_id'=>$node_id,'role_id'=>$role_id])->count();
        if($count>0){
            return true;
        }
        return false;
    }

    //3级目录
    public function getMenu()
    {
        if($this->is_super){
            $node_ids =  Db::table('rbac_role_node')->column('node_id');
        }else{
            $role_id = $this->user['role_id'];
            $node_ids =  Db::table('rbac_role_node')->where('role_id',$role_id)->column('node_id');
        }

        $nodes = Db::table('rbac_node')
            ->where(['is_access'=>0, 'position'=>'1','parent_id'=>0])
            ->select($node_ids);
        foreach ($nodes as &$node)
        {
            $node['children'] = Db::table('rbac_node')->where('parent_id',$node['id']);
            foreach ($node['children'] as &$child)
            {
                $child['children'] = Db::table('rbac_node')->where('parent_id',$node['id']);
            }
        }
        return $nodes;
    }







}